import {use, useReducer} from "react";
import {useImmerReducer} from "use-immer";


const UseImmerPage2 = () => {

  const reducer = (state: any, action: any) => {
    switch (action.type) {
      case 'update_name':
        state.name += action.newName
        return {...state} // 必须返回新的对象
        return {...state, name: state.name + action.newName} // 必须返回新的对象
      case 'update_score':
        state.score += action.step
        return {...state} // 必须返回新的对象
        return {...state, score: state.score + action.step}
      default:
        return {...state}
    }
  }
  const initialState = {
    name: '张三',
    age: 18,
    score: 21,
  }

  const [userInfo, dispatch] = useReducer(reducer, initialState)

  const reducer2 = (state: any, action: any) => {
    switch (action.type) {
      case 'update_name':
        state.name += action.newName // 直接改属性就够了，不用返回新的对象了
        break
      case 'update_score':
        state.score += action.step
        break
      default:
        break;
    }
  }
  const [userInfo2, dispatch2] = useImmerReducer(reducer2, initialState)
  return (
    <>

      <div>
        <h2>useReducer的使用对比</h2>
        <div>
          <span>姓名：{userInfo.name}</span>  &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
          <span>年龄：{userInfo.age}</span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
          <span>分数：{userInfo.score}</span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
        </div>

        <div>
          <button onClick={() => dispatch({type: 'update_name', newName: '~'})}>修改名字</button>
          <button onClick={() => dispatch({type: 'update_score', step: 2})}>修改分数</button>
        </div>
      </div>


      <div>
        <h2>useImmerReducer的使用</h2>
        <div>
          <span>姓名：{userInfo2.name}</span>  &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
          <span>年龄：{userInfo2.age}</span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
          <span>分数：{userInfo2.score}</span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
        </div>
        <div>
          <button onClick={() => dispatch2({type: 'update_name', newName: '~'})}>修改名字</button>
          <button onClick={() => dispatch2({type: 'update_score', step: 2})}>修改分数</button>
        </div>
      </div>
    </>
  )
}

export default UseImmerPage2;
